const router = require('koa-router')()
const { exec } = require('../utils/exec')
const { SuccessModel, FailModel } = require('../utils/resModel')
const { getPassword } = require('../utils/crypto')
const jwt = require('jsonwebtoken')
const { secretKey } = require('../utils/config')
router.prefix('/users')

router.post('/login', async function (ctx, next) {
  const { username, password } = ctx.request.body
  const loginData = await exec(
    `select * from users where username=? and password=?`,
    [username, getPassword(password)]
  )
  const token = jwt.sign(
    {
      id: loginData[0].id,
      username: loginData[0].username,
    },
    secretKey,
    { expiresIn: '24h' }
  )
  ctx.body = new SuccessModel({ token })
})

router.post('/register', async (ctx, next) => {
  const { username, password, avatar, nickname, gender } = ctx.request.body
  try {
    const sql = `insert into users (username, password, nickname, avatar,gender) 
    values (?,?,?,?, ?)`
    const registerData = await exec(sql, [
      username,
      getPassword(password),
      nickname,
      avatar,
      gender,
    ])
    ctx.body = new SuccessModel(registerData)
  } catch (err) {
    ctx.body = new FailModel(registerData)
  }
})

// 用户查询接口 分页
router.get('/list', async (ctx, next) => {
  const { page = 1, size = 5 } = ctx.query
  /**
   * @fun 添加权限
   * 1. 拿到用户信息 ctx.state.userInfo => id
   * 2. id =1 是超级管理员
   * 3. id !==1 的时候，每个人只能拿到拿到每个人自己的数据
   */
  try {
    const { id } = ctx.state.userInfo
    let totalSql = `select count(id) as total from users;`
    let sql = `select * from users where 1+1 `
    let userData
    if (id !== 1) {
      sql += `and id = ?`
      userData = await exec(sql, [id])
    } else {
      sql += `limit ? offset ?`
      userData = await exec(sql, [size * 1, (page - 1) * size * 1])
    }
    const total = await exec(totalSql)
    ctx.body = new SuccessModel({ total: total[0].total, userData })
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})

// select * from users where username like '%镇%' and password ='123';

// 模糊搜索接口
router.get('/search', async (ctx, next) => {
  const { keywords } = ctx.query
  try {
    const sql = `select * from users where username like '%${keywords}%'`
    const data = await exec(sql)
    ctx.body = new SuccessModel(data)
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})
// 暂时接口 （修改用户密码）
router.put('/list', async (ctx, next) => {
  // 修改用户信息
  const { password, id } = ctx.request.body
  const sql = `update users set password=? where id=?`
  const updateData = await exec(sql, [getPassword(password), id])
  ctx.body = new SuccessModel(updateData)
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

router.get('/get-test', async (ctx, next) => {
  ctx.body = {
    code: 0,
    msg: '测试接口',
  }
})

module.exports = router
